
function Promise(executor){
    const self = this;
    self.promiseState = 'pending';
    self.promiseResult = undefined;
    self.callbacks = [];
    function success(value){
        //判断
        if(self.promiseState !== 'pending') return;
        // success 修改状态
        self.promiseState = 'fulfilled';
        // 赋值成功的结果值
        self.promiseResult = value;
        //执行成功的回调
        self.callbacks.forEach(item => {
            //执行成功的回调
            item.ok();
        });
    }

    function error(reason){
        if(self.promiseState !== 'pending') return;
        // success 修改状态
        self.promiseState = 'rejected';
        // 赋值成功的结果值
        self.promiseResult = reason;
        //执行成功的回调
        self.callbacks.forEach(item => {
            //执行成功的回调
            item.fail();
        });
    }

    try{
        //执行器函数是同步调用的
        executor(success, error);
    }catch(e){
        error(e);
    }
}

Promise.prototype.then = function(onFulfilled, onRejected){
    return new Promise((resolve, reject) => {
        //判断
        if(this.promiseState === 'fulfilled'){
            //获取回调的执行结果
            let rs = onFulfilled(this.promiseResult);
            //判断
            if(rs instanceof Promise){
                rs.then(resolve, reject);
            }else{
                resolve(rs);
            }
        }

        if(this.promiseState === 'rejected'){
            let rs = onRejected(this.promiseResult);
            //判断
            if(rs instanceof Promise){
                rs.then(resolve, reject);
            }else{
                resolve(rs);
            }
        }

        if(this.promiseState === 'pending'){
            //不能立即执行回调, 保存回调
            this.callbacks.push({
                ok: () => {
                    //执行 then 方法传入的成功的回调
                    let rs = onFulfilled(this.promiseResult);
                    //判断
                    if(rs instanceof Promise){
                        rs.then(resolve, reject);
                    }else{
                        resolve(rs);
                    }
                },
                fail: () => {
                    //执行失败的回调
                    let rs = onRejected(this.promiseResult);
                    //判断
                    if(rs instanceof Promise){
                        rs.then(resolve, reject);
                    }else{
                        resolve(rs);
                    }
                }
            })
        }
    })
}